<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <div class="search">
        <el-input
          placeholder="请输入内容"
          v-model="params.query"
          @keyup.enter.native="getUserList"
          clearable
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="search"
          ></el-button>
        </el-input>
        <el-button type="primary" class="add" @click="dialogFormVisible = true">
          添加用户
        </el-button>
      </div>
      <!-- 用户列表区域 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 作用域插槽渲染状态这一列 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 编辑用户 -->
            <el-tooltip content="修改用户" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditUser(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 删除用户 -->
            <el-tooltip content="删除用户" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delUser(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色 -->
            <el-tooltip content="分配角色" placement="top">
              <el-button
                icon="el-icon-setting"
                size="mini"
                type="warning"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pagenum"
          :page-sizes="[2, 4, 5, 10]"
          :page-size="params.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 添加用户 对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      width="40%"
      @close="dialogClose"
    >
      <el-form
        :model="form"
        :rules="addFormRules"
        label-width="70px"
        ref="addFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户 对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogEditVisible"
      width="40%"
     
     @close="closeEdit"
    >
      <el-form
        :model="editForm"
        :rules="addFormRules"
        label-width="70px"
        ref="editRef"
      >
        <el-form-item label="用户名" prop="username" disabled>
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="dialogSetVisible" width="40%">
      <p>当前的用户: {{ userRoles.username }}</p>
      <p>当前的角色: {{ userRoles.role_name }}</p>
      <el-form :model="userRoles">
        <el-form-item label="分配新角色">
          <el-select placeholder="请选择" v-model="selectedRoled">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSetVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    const checkEmail = (rule, value, callback) => {
      const reg =
        /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 手机号验证
    const checkMobile = (rule, value, callback) => {
      const reg = /^((\+|00)86)?1[3-9]\d{9}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }

    return {
      // 用户列表数据
      tableData: [],
      //总条数
      total: 0,
      // 请求携带参数
      params: {
        query: '',
        // 当前页
        pagenum: 1,
        // 每页条数
        pagesize: 2
      },
      // 控制添加用户显示与隐藏
      dialogFormVisible: false,
      // 控制修改用户
      dialogEditVisible: false,
      // 控制分配角色
      dialogSetVisible: false,
      // 添加用户携带参数

      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑用户
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色信息
      userRoles: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRoled: '',
      formLabelWidth: '70px',
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '用户名长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        // 验证密码是否合法
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 16,
            message: '密码长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 用户列表请求函数
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.params
      })
      this.tableData = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.params.pagesize = val
      this.getUserList()
    },
    //当前页数发生改变
    handleCurrentChange(val) {
      this.params.pagenum = val
      this.getUserList()
    },
    // 添加用户
    async adduser() {
      console.log(this.$refs.addFormRef)
      const { data: res } = await this.$http.post('users', this.form)
      if (res.meta.status === 201) {
        this.getUserList()
        console.log(res)
        this.$message.success('添加用户成功!')
        this.dialogFormVisible = false
      } else {
        this.$message.error('添加用户失败')
      }
    },
    // 监听添加对话框的的关闭事件
    dialogClose() {
      // 关闭时清空表单
      this.$refs.addFormRef.resetFields()
    },
    // 查询
    search() {
      this.getUserList()
    },
    async userStateChanged(e) {
      const { data: res } = await this.$http.put(
        `users/${e.id}/state/${e.mg_state}`
      )
      // console.log(res);
      // console.log(e);
      if (res.meta.status !== 200) {
        e.mg_state = !e.mg_state
        return this.$message.error('更新用户状态失败!')
      }
      this.$message.success('更新用户状态成功!')
    },
    // 展示编辑用户
    showEditUser(e) {
      console.log(e)
      // this.editForm.username = e.username
      // this.editForm.email = e.email
      // this.editForm.mobile = e.mobile
      // this.editForm.id = e.id
      this.editForm = e
      this.dialogEditVisible = true
    },
    // 编辑用户
    async editUser() {
      if(this.editForm.username === 'admin') return this.$message.error('不允许对admin用户进行修改')
      // 可以发送修改用户的网络请求
      const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
        email: this.editForm.email,
        mobile: this.editForm.mobile
      })
      if (res.meta.status !== 200) {
        this.$message.error('更新失败')
      }
      this.getUserList()
      console.log(res)
      this.$message.success('更新成功')
      this.dialogEditVisible = false
    },
    closeEdit() {
      this.$refs.editRef.resetFields()
    },
    // 删除用户
     async delUser(e) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${e.id}`)
          if (res.meta.status === 200) {
            console.log(1)
            this.getUserList()
            this.$message.success('删除成功')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配角色
    async setRole(e) {
      console.log(e)
      this.userRoles = e

      // 在展示对话框之前, 获取所有的角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!')
      }

      this.rolesList = res.data
      console.log(this.rolesList)

      this.dialogSetVisible = true
    },
    async saveRoleInfo() {
      if (!this.selectedRoled) {
        return this.$message.error('请选择角色')
      }
      if (this.userRoles.username === 'admin') {
        this.dialogSetVisible = false
        return this.$message.error('不允许对admin用户进行修改')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userRoles.id}/role`,
        {
          rid: this.selectedRoled
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败!')
      } else {
        this.getUserList()
        // 隐藏对话框
        this.dialogSetVisible = false
        return this.$message.success('更新角色成功!')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  display: flex;
  justify-content: space-between;
  width: 500px;
  .add {
    margin-left: 20px;
  }
}
</style>
